package com.jketing.controller.ams.base;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jketing.controller.BaseController;
import com.jketing.entity.ams.base.Dictionary;
import com.jketing.service.ams.base.DictionaryService;

/**
 * Controller 请求处理
 * 
 * @author  李荣华
 * @version v1.0
 * @date    2017-08-19
 * @since   Spring-mvc 4.3.8
 */
@Controller
@RequestMapping("/dictionary")
public class DictionaryController extends BaseController<Dictionary,String>{

	/**
	 *  service 	服务层引用
	 */
	private DictionaryService service;
	/**
	 *  spring 自动注入服务层操作实例
	 */
	@Autowired
	public void setService(DictionaryService service) {
		super.setBaseService(service);
		this.service = service;
	}
	
	@Override
	protected String getPrefixPath() {
		return "base/dictionary/";
	}

	@Override
	protected String getQueryMode() {
		return "Entity";
	}
	
	/**
	 * 公共调用方法
	 * 按照英文类型名获取数据字典列表
	 * @return
	 */
	@RequestMapping("/getCodeList")
	public void getCodeList(String enName,Map<String, Object> map) {
		map.put("codeList", service.getPropertyByEnName(enName));
	}
	
	@Override
	protected Dictionary getQuery(Dictionary query) {
		String type = (String)getSession().getAttribute("dictionary_type");
		if("redirect".equals(type)) {
			if("Entity".equals(getQueryMode())) {
				query = (Dictionary)getSession().getAttribute("dictionary_query");
			}
		}
		request.setAttribute("list", service.getDictionaryByTypeCode(1));
		//可在此处增加修改查询条件的代码
		return query;
	}
	
	/**
	 *  初始化新增编辑页
	 */
	@Override
	protected void initAdd(Map<String, Object> map) {
		map.put("list", service.getDictionaryByTypeCode(1));
	}
	
	/**
	 *  初始化更新编辑页
	 */
	@Override
	protected void initEdit(Map<String, Object> map) {
		Dictionary entity = (Dictionary)map.get("entity");
		List<Dictionary> list = new ArrayList<Dictionary>();
		list.add(entity.getParent());
		map.put("list", list);
	}
	
	/**
	 * checkEnName 异步请求校验英文名称，返回字符串数据
	 * 
	 * @return 无返回，直接向response里写数据
	 */
	@RequestMapping(value="/checkEnName",method=RequestMethod.POST)
	@ResponseBody
	public String checkEnName(String fieldId,String fieldValue){
		StringBuilder sb = new StringBuilder();
		if(service.checkEnName(fieldValue)){
			sb.append("[\""+fieldId+"\","+false+"]");
		}
		else{
			sb.append("[\""+fieldId+"\","+true+"]");
		}
		return sb.toString();
	}
}
